#include "EpollHandle.h"
#include "common.h"
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <netdb.h>
#include <unistd.h>
#include <arpa/inet.h>


EpollHandle::EpollHandle( int listenfd, EPollObserver *ob)
{
    if((this->epollfd_ = epoll_create(EPOLL_SIZE)) == -1)
        ERR_EXIT("epoll_create");
    this->listenfd_ = listenfd;
    this->nready_ = 0;
    this->mObserver = ob;

    std::cout << this->epollfd_ <<" -- "<< this->listenfd_ << "  in EpollHandle\n";
}
EpollHandle::~EpollHandle()
{}
void EpollHandle::epoll_do_wait()
{
    tStart = clock();
    int nready;
    do{
        nready = epoll_wait(this->epollfd_, this->events_, EPOLL_SIZE, EPOLL_RUN_TIMEOUT);
        if(nready > 0)
            std::cout << nready << "  in epoll_do_wait\n";
    }while(nready == -1 && errno ==  EINTR);
    if(nready == -1)
        ERR_EXIT("epoll_wait");
    this->nready_ = nready;
}
void EpollHandle::epoll_handle()
{
    int i;
    for(i = 0 ; i < this->nready_; i++)
    {
        int fd = this->events_[i].data.fd;
        int tag = 0; // 0: 处理其他端口数据读写， 1:  接受新加入
        if(fd == this->listenfd_)
        {
            tag = 1;
        }
        
         this->mObserver->OnHandleData(fd, tag);
    }
   // printf("Statistics: %d events handled at: %.2f second(s)\n", this->nready_, (double)(clock() - tStart)/CLOCKS_PER_SEC);
}
void EpollHandle::epoll_close()
{
    ::close(this->epollfd_);
}

void EpollHandle::epoll_add_fd(int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    ev.events = EPOLLIN; //| EPOLLET; 
    if(epoll_ctl(this->epollfd_, EPOLL_CTL_ADD, fd, &ev) == -1)
        ERR_EXIT("epoll_ctl");
}
void EpollHandle::epoll_del_fd(int fd)
{
    struct epoll_event ev;
    ev.data.fd = fd;
    if(epoll_ctl(this->epollfd_, EPOLL_CTL_DEL, fd, &ev) == -1)
        ERR_EXIT("epoll_ctl");
}
